<%--商品管理页--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>商品管理页</title>
  <jsp:include page="/static/back/common/links.jsp" flush="true" />
  <link href="${ROOT_PATH}/static/back/css/jquery.fileupload.css" rel="stylesheet"/>


  <style>
    .input-group-text{
      background-color: #FFFFFF;
    }

    .bar {
      height: 25px;
      background: #6c757d;
      border-radius: 4px;
      color: #fff;
    }

    .upload {
      margin-bottom: 20px;
    }

    .upload_content {
      margin-bottom: 10px;
      display: flex;

    }

    .upload_thumb {
      margin-left: 30px;
      width: 100px;
      height: 100px;
      overflow: hidden;
      display: none;
      text-align: center;
      position: relative;
    }

    .upload_thumb img {
      position: absolute;
      left: 50%;
    }



  </style>
</head>

<body class="fixed-nav sticky-footer bg-dark" id="page-top">
  <!-- Navigation-->
  <jsp:include page="/static/back/common/nav.jsp" flush="true" />

  <div class="content-wrapper">
    <div class="container-fluid">
      <!-- Breadcrumbs-->
      <ol class="breadcrumb">
        <li class="breadcrumb-item">
          <a href="#">OxyGen</a>
        </li>
        <li class="breadcrumb-item active">商品管理</li>
      </ol>
      <!-- Example DataTables Card-->
      <div class="card mb-3">
        <div class="card-header">
          <i class="fa fa-table"></i> 商品信息
          <button style="margin-left: 84%" type="button" class="btn btn-outline-primary" id="add_btn">新增商品</button>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table id="table">
            </table>
            <%--新增的模态框--%>
            <!-- 模态框 -->
            <div class="modal fade" id="myModal">
              <div class="modal-dialog">
                <div class="modal-content">

                  <!-- 模态框头部 -->
                  <div class="modal-header">
                    <h4 class="modal-title">商品新增</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                  </div>

                  <!-- 模态框主体 -->
                  <div class="modal-body">
                    <form id="my_form">
                      <div class="upload">
                        <div class="upload_content">
                          <div class="upload_file_content">
                                <span class="btn btn-secondary fileinput-button">
                                            <i class="glyphicon glyphicon-plus"></i>
                                            <span>选择一张图片</span>
                                            <input type="file" id="fileupload" name="file">
                         </span>
                          </div>
                          <div class="upload_thumb">
                            <%--<img src="" id="thumb_img"/>--%>
                          </div>
                        </div>
                        <div id="progress">
                          <div class="bar" style="width: 0%;"></div>
                        </div>
                      </div>


                      <div class="form-group">
                        <div class="input-group mb-3">
                          <label for="name" class="col-sm-3 control-label">商品名</label>
                          <div class="col-sm-9">
                            <input type="text" class="form-control" id="name" placeholder="商品名">
                          </div>
                        </div>
                        <div class="input-group mb-3">
                          <label for="price" class="col-sm-3 control-label">单价</label>
                          <div class="col-sm-9">
                            <input type="text" class="form-control" id="price" placeholder="单价" />
                          </div>
                        </div>

                        <div class="input-group mb-3 commodity">
                          <div class="input-group mb-3">
                          <span class="input-group-text col-sm-12">商品属性
                            <div style="margin-left: 64%;">

                                <button id="add_attr_btn" data-toggle="tooltip" data-placement="top" title="新增商品的属性、样式"
                                        type="button" class="btn btn-outline-primary">
                                  <span class="fa fa-fw fa-plus"></span>
                                </button>
                                <button id="del_attr_btn" data-toggle="tooltip" data-placement="top" title="删除刚增加的属性、样式"
                                        type="button" class="btn btn-outline-danger">
                                  <span class="fa fa-fw fa-minus"></span>
                                </button>

                            </div>
                          </span>
                          </div>
                          <div class="input-group mb-3 commodity_commons">
                          </div>
                        </div>
                      </div>
                    </form>
                  </div>

                  <!-- 模态框底部 -->
                  <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="add_form_btn">提交</button>
                    <button type="button" class="btn btn-primary" id="update_form_btn">保存</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div>
      </div>
    </div>
    <jsp:include page="/static/back/common/scripts.jsp" flush="true" />
    <jsp:include page="/static/back/common/footer.jsp" flush="true" />
  </div>
</body>
<script src="${ROOT_PATH}/static/back/js/jquery.ui.widget.js"></script>
<script src="${ROOT_PATH}/static/back/js/jquery.iframe-transport.js"></script>
<script src="${ROOT_PATH}/static/back/js/jquery.fileupload.js"></script>
<script>
    $(function() {

        /*
        *查询操作
        * */
        let url = "${ROOT_PATH}" + "/back/commodity/selectAll";

        //初始化数据
        $('#table').bootstrapTable({
            url: url,
            search: true,
            striped: true,
            clickToSelect: true,
            uniqueId: "id",
            sortable: true,
            sortOrder: "asc",
            sidePagination: "server",
            showAllColumns: true,
            showRefresh: true,
            pagination: true,
            pageNumber: 1,
            pageSize: 10,
            queryParamsType: "",
            columns: [
                {"field": "id", "title": "id"},
                {"field": "name", "title": "商品名称"},
                {"field": "price", "title": "价格"},
                {"field": "backCommodityTypeList", "title": "商品属性汇总", formatter: typeListFormatter},
                {"field": "commoditySalesNum", "title": "销售额"},
                {"field": "frontCommodityThumbnail", "title": "商品缩略图"},
                {"field": "state", "title": "状态", formatter: stateFormatter},
                {"field": "lastAwayTime", "title": "下架时间"},
                {"field": "putawayTime", "title": "上架时间"},
                {"field": "createTime", "title": "创建时间"},
                {"field": "updateTime", "title": "更新时间"},
                {
                    "field": "id",
                    "title": "操作",
                    width: 180,
                    align: "center",
                    valign: "middle",
                    formatter: actionFormatter
                }
            ]
        });

        //操作按钮格式化
        function actionFormatter(value, row, index) {
            let id = value;
            let rows = $("#table").bootstrapTable('getRowByUniqueId', id);
            let result = "";
            if (rows.state === 0){
                result += `<a href='javascript:;' class='btn btn-xs blue undercarriage_btn'  title='点击下架' data-id="\${id}"><span class='glyphicon glyphicon-hand-down'></span></a>`;
            }else {
                result += `<a href='javascript:;' class='btn btn-xs blue grounding_btn'  title='点击上架' data-id="\${id}"><span class='glyphicon glyphicon-hand-up'></span></a>`;
            }
            result += `<a href='javascript:;' class='btn btn-xs blue update_btn'  title='编辑' data-id="\${id}"><span class='glyphicon glyphicon-pencil'></span></a>`;
            result += `<a href='javascript:;' class='btn btn-xs red del_btn'  title='删除'   data-id="\${id}"><span class='glyphicon glyphicon-remove'></span></a>`;
            return result;
        }

        //类型列表格式化
        function typeListFormatter(value, row, index) {
            let htmlObj = {};
            value.forEach(function (e, i) {
                if (htmlObj[e.frontCommodityType] === undefined) {
                    htmlObj[e.frontCommodityType] = [];
                    htmlObj[e.frontCommodityType].push(e.frontCommodityTypeParameter);
                } else {
                    htmlObj[e.frontCommodityType].push(e.frontCommodityTypeParameter);
                }
            });
            let htmlStr = "";
            for (i in htmlObj) {
                let attribute_arr = htmlObj[i];
                htmlStr += i + ":";
                htmlStr += attribute_arr.join(",");
                htmlStr += "<br/>";
            }
            return htmlStr;


        }

        //商品状态格式化
        function stateFormatter(value, row, index) {
            if (value === 0) {
                return "已上架";
            }
            return "已下架";
        }

        //打开更新商品表单界面
        $(document).on("click", ".update_btn", function () {

            $(".modal-title").html("修改商品");
            $("#add_form_btn").hide();
            $("#update_form_btn").show();
            $(".bar").css("width", "0%");
            let id = $(this).attr("data-id");
            if ($("#id").length === 0) {
                $("#my_form").append(`<input name="id" value="\${id}" id="id" type="hidden" />`);
            } else {
                $("#id").val(id);
            }
            let row = $("#table").bootstrapTable('getRowByUniqueId', id);

            imgUrl = row.frontCommodityThumbnail;
            $(".upload_thumb").css({
                "background-image": "url(${ROOT_PATH}/file/" + imgUrl + ") ",
                "background-position": "center"
            }).show();
            $("#name").val(row.name);
            $("#price").val(row.price);
            $(".commodity_commons").remove(); //清空所有属性-属性值对
            $("#myModal").modal("show");
            row.backCommodityTypeList.forEach(function (e, i) {
                let htmlStr = `<div class="input-group mb-3 commodity_commons">
                                         <input type="text" class="form-control commodity_type" placeholder="商品属性" value="\${e.frontCommodityType}"/>
                                         <input type="text" class="form-control commodity_type_parameter" value="\${e.frontCommodityTypeParameter}" placeholder="商品属性值"/>
                                         <input type="hidden"  value="\${e.id}" class="commodity_id"/>
                                         <button data-toggle="tooltip" data-placement="top" title="删除本行的属性、样式" type="button" class="btn btn-danger del_now_attr_btn">
                                  <span class="fa fa-fw fa-minus"></span>
                                </button>
                                  </div>`;
                $(".commodity").append(htmlStr);
            });
            $('[data-toggle="tooltip"]').tooltip();

        });

        //进行更新操作
        $("#update_form_btn").click(function () {
            if (($("#name").val() && $(".commodity_type_parameter").val() && $(".commodity_type").val() && $("#price").val() && imgUrl) != null && ($("#name").val() && $(".commodity_type_parameter").val() && $(".commodity_type").val() && $("#price").val() && imgUrl) != "") {
                let commodity = {};//商品的对象
                let commodityTypeArr = [];//商品属性与值存放的数组

                let btns = $('.commodity_commons');//遍历这个div的class
                btns.each(function (i, e) {
                    let commodityType = {};//商品样式的对象
                    commodityType.frontCommodityTypeParameter = $(this).find(".commodity_type_parameter").val();//商品属性值
                    commodityType.frontCommodityType = $(this).find(".commodity_type").val();//商品所拥有的属性
                    commodityType.id = $(this).find(".commodity_id").val();//商品所拥有的属性
                    commodityTypeArr.push(commodityType);//把每次获取的值，放到这个数组里

                }, false);
                commodity.id = $("#id").val();
                commodity.frontCommodityThumbnail = imgUrl;//商品图片的url
                commodity.name = $("#name").val();//商品的名字
                commodity.price = $("#price").val();//商品的单间
                commodity.backCommodityTypeList = commodityTypeArr;//把商品属性与值存放的数组放到这个对象
                $.ajax({
                    url: "${ROOT_PATH}/back/commodity/update",
                    data: JSON.stringify(commodity),
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json",
                    success: function (res) {
                        if (res["error"] === false) {
                            $('#myModal').modal('hide');
                            alert(res["msg"]);
                            $("#table").bootstrapTable('refresh', {silent: true});
                        }

                    }

                });
            } else {
                alert("内容或上传图片都不能为空！");
            }
        });


        //打开添加商品表单界面
        $("#add_btn").click(function () {
            $(".modal-title").html("添加商品");
            //还原现场
            $("#add_form_btn").show();
            $("#update_form_btn").hide();
            $("#id").remove();
            $(".upload_thumb").css({"background-image": "", "background-position": ""}).hide();
            $(".bar").css("width", "0%");
            $("#name").val("");
            $("#price").val("");
            $(".commodity_commons").remove();
            $(".commodity").append(`<div class="input-group mb-3 commodity_commons">
                            <input type="text" class="form-control commodity_type" placeholder="商品属性">
                             <input type="text" class="form-control commodity_type_parameter" placeholder="商品属性值">
                               <button data-toggle="tooltip" data-placement="top" title="删除本行的属性、样式" type="button" class="btn btn-danger del_now_attr_btn">
                                  <span class="fa fa-fw fa-minus"></span>
                                </button>
                             </div>`);
            imgUrl = ""; //清空img存储路径

            $("#myModal").modal("show");
        });
        //上传图片
        let imgUrl = "";
        $('#fileupload').fileupload({
            dataType: 'json',
            url: "${ROOT_PATH}/back/commodity/upload",
            // 上传完成后的执行逻辑
            done: function (e, data) {
                imgUrl = data.result.data.imgUrl;
                <%--$("#thumb_img").attr("src","${ROOT_PATH}/file/"+imgUrl);--%>
                $(".upload_thumb").css({
                    "background-image": "url(${ROOT_PATH}/file/" + imgUrl + ") ",
                    "background-position": "center"
                }).show();
            },
            // 上传过程中的回调函数
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $(".bar").text(progress + '%');
                $('#progress .bar').css(
                    'width',
                    progress + '%'
                );
            }
        });
        //添加商品的属性与值
        $("#add_attr_btn").click(function () {

            let str = `<div class="input-group mb-3 commodity_commons">
                            <input type="text" class="form-control commodity_type" placeholder="商品属性">
                             <input type="text" class="form-control commodity_type_parameter" placeholder="商品属性值">
                               <button data-toggle="tooltip" data-placement="top" title="删除本行的属性、样式" type="button" class="btn btn-danger del_now_attr_btn">
                                  <span class="fa fa-fw fa-minus"></span>
                                </button>
                             </div>`;

            $(".commodity").append(str);

        });

        //删除当前行商品的属性与值
        $(document).on("click", ".del_now_attr_btn", function () {
            let len = $(".commodity_commons").length;
            if (len > 1) {
                $(this).parent(".commodity_commons").remove();
            } else {
                alert("至少要有一个属性");
            }

        });

        //删除商品的属性与值
        $("#del_attr_btn").click(function () {
            let len = $(".commodity_commons").length;
            if (len > 1){
                $(".commodity").children("div:last-child").remove();
            }else {
                alert("至少要有一个属性");
            }

        });
        //执行添加商品操作
        $("#add_form_btn").click(function () {

            if (($("#name").val() && $(".commodity_type_parameter").val() && $(".commodity_type").val() && $("#price").val() && imgUrl) != null && ($("#name").val() && $(".commodity_type_parameter").val() && $(".commodity_type").val() && $("#price").val() && imgUrl) != ""){
                let commodity = {};//商品的对象
                let commodityTypeArr = [];//商品属性与值存放的数组

                let btns = $('.commodity_commons');//遍历这个div的class
                btns.each(function(i, e) {
                    let commodityType = {};//商品样式的对象
                    commodityType.frontCommodityTypeParameter = $(this).find(".commodity_type_parameter").val();//商品属性值
                    commodityType.frontCommodityType = $(this).find(".commodity_type").val();//商品所拥有的属性
                    commodityTypeArr.push(commodityType);//把每次获取的值，放到这个数组里

                }, false);

                commodity.frontCommodityThumbnail = imgUrl;//商品图片的url
                commodity.name = $("#name").val();//商品的名字
                commodity.price = $("#price").val();//商品的单间
                commodity.backCommodityTypeList = commodityTypeArr;//把商品属性与值存放的数组放到这个对象
                $.ajax({
                    url: "${ROOT_PATH}/back/commodity/addCommodity",
                    data: JSON.stringify(commodity),
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json",
                    success: function(res) {
                        // console.log(res["error"]);
                        // console.log(res["msg"]);
                        // console.log(res["data"]);
                        if (res["error"] === false){
                            $('#myModal').modal('hide');
                            alert(res["msg"]);
                            $("#table").bootstrapTable('refresh', {silent: true});
                        }

                    }

                });
            }else {
                alert("内容或上传图片都不能为空！");
            }
        });

        // 删除商品
        $(document).on("click", ".del_btn", function () {
            let id = $(this).attr("data-id");
            let dele = confirm("是否删除？");
            if (dele) {
                $.ajax({
                    url: "${ROOT_PATH}/back/commodity/delete",
                    data: {id: id},
                    dataType: "json",
                    type: "POST",
                    success: function (res) {
                        if (res["error"] === false) {
                            alert("删除成功!");
                            $("#table").bootstrapTable('refresh', {silent: true});
                        }
                    }
                });
            }

        });

        //修改商品状态 （下架）
        $(document).on("click", ".undercarriage_btn", function () {
            let id = $(this).attr("data-id");
            let undercarriage = confirm("是否将该商品下架？");
            if (undercarriage) {
                $.ajax({
                    url: "${ROOT_PATH}/back/commodity/undercarriage",
                    data: {id: id},
                    dataType: "json",
                    type: "POST",
                    success: function (res) {
                        if (res["error"] === false) {
                            alert("下架成功!");
                            $("#table").bootstrapTable('refresh', {silent: true});
                        }
                    }
                });
            }
        });

        //修改商品状态 （上架）
        $(document).on("click", ".grounding_btn", function () {
            let id = $(this).attr("data-id");
            let grounding = confirm("是否将该商品上架？");
            if (grounding) {
                $.ajax({
                    url: "${ROOT_PATH}/back/commodity/grounding",
                    data: {id: id},
                    dataType: "json",
                    type: "POST",
                    success: function (res) {
                        if (res["error"] === false) {
                            alert("上架成功!");
                            $("#table").bootstrapTable('refresh', {silent: true});
                        }
                    }
                });
            }
        });

        //初始化提示工具
        $('[data-toggle="tooltip"]').tooltip();
    });

</script>
</html>
